using Cysharp.Threading.Tasks;
using Framework.Helper;
using Framework.Manager;
using Framework.Network;
using Framework.UI;
using Game.Model.ServerList;
using Game.System;
using LitJson;
using Shared.App;
using Shared.UI;
using UnityEngine;

namespace Game.Logic.Auth
{
    public class Auth : UIController
    {
        private Login.Login login;

        protected override async UniTask RequestProtocol()
        {
            await Active<UIController>(UIId.Connecting);
            
            string serverStr = await HttpHelper.HttpGet(AppDefine.ServerListCmd);
            Debug.Log("=====  " + serverStr);
            ServerDto serverDto = JsonMapper.ToObject<ServerDto>(serverStr);
            // Debug.Log("-------  " + serverDto.errorCode + "  " + serverDto.detail.Count);

            AccountSystem.Instance.serverList = serverDto.detail;
            AccountSystem.Instance.SetSelect();

            // 创建连接
            ServerInfoDto serverInfo = AccountSystem.Instance.GetCurrentServer();
            // Debug.Log("AA  " + serverInfo.host + " " + serverInfo.port);
            SocketMessage connect = await NetworkManager.Instance.ConnectAsync(NetUtil.LobbyConnect, serverInfo.ip, serverInfo.port, SocketProtocolType.TcpMoon);
            if (connect == null)
            {
                Debug.Log($"create connection fail.");
                return;
            }
            AccountSystem.Instance.SetConnection(connect.ConnectId);

            await Deactive(UIId.Connecting);
        }

        protected override async UniTask OnRefreshUI()
        {
            login = await Active<Login.Login>(UIId.Login);
        }
    }
}